package lauglog.servlet;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;
import java.util.Vector;
import lauglog.bean.UserBean;
import lauglog.util.MadePlan;
import lauglog.util.MetricData;
import lauglog.util.StaticData;

/**
 *
 * @author Waseem
 */
@WebServlet(name = "Analytics", urlPatterns = {"/Analytics"})
public class AnalyticsServlet extends HttpServlet {
    
    int eventCounter = 0;

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            String action = request.getParameter("action");
            if (action.equalsIgnoreCase("userQuery"))
                userQuery(request,response);
            else if (action.equalsIgnoreCase("doctorQuery"))
                doctorQuery(request,response);
            else if (action.equalsIgnoreCase("getEvents"))
                getEventsByPlan(request,response);
            else if (action.equalsIgnoreCase("generateChart")){
                generateChart(request,response);
            }else if (action.equalsIgnoreCase("getPatientData")){
                getPatientData(request,response);
            }
            else;
        } finally {            
            out.close();
        }
    }
    
    private void getPatientData(HttpServletRequest request, HttpServletResponse response){
        //Initiate variables for database queries
        String url = "jdbc:mysql://localhost/lauglog";
        String dbUserName = "root";
        String dbPassword = "";
        String driver = "com.mysql.jdbc.Driver";
        Connection con = null;
        try{
             //Make the connection
            Class.forName(driver).newInstance();
            con = DriverManager.getConnection(url, dbUserName, dbPassword);
            
            PrintWriter out = response.getWriter();
            
            
            
            int patientId = Integer.parseInt(request.getParameter("patientId"));
            request.getSession().setAttribute("tmpId", new Integer(patientId));
            PreparedStatement patientPlansStatement = con.prepareStatement("SELECT p.PlanId, p.PlanName FROM joined_plans jp INNER JOIN plans p ON p.PlanId = jp.PlanId AND jp.UserId = ?");
            patientPlansStatement.setInt(1, patientId);
            ResultSet patientPlansRs = patientPlansStatement.executeQuery();
            
            Vector<MadePlan> plans = new Vector();
            while(patientPlansRs.next()){
                MadePlan m = new MadePlan();
                m.setPlanID(patientPlansRs.getInt("PlanId"));
                m.setPlanName(patientPlansRs.getString("PlanName"));
                plans.add(m);
            }
            
            request.getSession().setAttribute("patientPlans", plans);
            response.sendRedirect("patientData.jsp");
            
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            try{
                con.close();
            }catch(Exception e){
                
            }
        }
    }
    
    private void userQuery(HttpServletRequest request, HttpServletResponse response){
        
    }
    
    private void doctorQuery(HttpServletRequest request, HttpServletResponse response){
        
    }
    
    private void getEventsByPlan(HttpServletRequest request, HttpServletResponse response){
        //Initiate variables for database queries
        String url = "jdbc:mysql://localhost/lauglog";
        String dbUserName = "root";
        String dbPassword = "";
        String driver = "com.mysql.jdbc.Driver";
        Connection con = null;
        try{
            
            
            
             //Make the connection
            Class.forName(driver).newInstance();
            con = DriverManager.getConnection(url, dbUserName, dbPassword);
            
            PrintWriter out = response.getWriter();
            
            int planId = Integer.parseInt(request.getParameter("planId"));
            PreparedStatement getEventsStatement = con.prepareStatement("SELECT * FROM events WHERE PlanId = ?");
            getEventsStatement.setInt(1, planId);
            ResultSet eventsRs = getEventsStatement.executeQuery();
            
            
            String json =   "{\"event\" : [";
            
            while(eventsRs.next()){
                json +=         "{\"name\" : \""+eventsRs.getString("Name")+"\", "
                              + "\"id\" : \""+eventsRs.getInt("EventId") +"\","
                              + "\"type\" : \""+eventsRs.getString("Type")+"\","
                              + "\"days\" : \""+eventsRs.getString("DayOfWeek")+"\"},";
            }
            
            json = json.substring(0, json.length()-1);
            json +=                     "]}";
            
            out.print(json);
            
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            try{
                con.close();
            }catch(Exception e){
                
            }
        }
    }
    
    private void generateChart(HttpServletRequest request, HttpServletResponse response){
        
        int eventId = Integer.parseInt(request.getParameter("eventId"));
        String type;
        String name;
        
        //Initiate variables for database queries
        String url = "jdbc:mysql://localhost/lauglog";
        String dbUserName = "root";
        String dbPassword = "";
        String driver = "com.mysql.jdbc.Driver";
        Connection con = null;
        try{
             //Make the connection
            Class.forName(driver).newInstance();
            con = DriverManager.getConnection(url, dbUserName, dbPassword);
            
            PreparedStatement eventTypeStatement = con.prepareStatement("SELECT Type, Name FROM events WHERE EventId = ?");
            eventTypeStatement.setInt(1, eventId);
            ResultSet eventTypeRs = eventTypeStatement.executeQuery();
            eventTypeRs.first();
            name = eventTypeRs.getString("Name");
            type = eventTypeRs.getString("Type");
            if(null == type){
                response.getWriter().print("");
                return;
            }
            
            int id;
            if(request.getParameter("url").contains("patientData")){
                id = (Integer)request.getSession().getAttribute("tmpId");
                System.out.println("ID FROM DOCTOR: "+id);
            }
            else{
                id = ((UserBean)request.getSession().getAttribute("user")).getUserID();
                System.out.println("ID FROM PATIENT:"+id);
            }
            
            if("metric".equalsIgnoreCase(type)){
                
                PreparedStatement dataStatement = con.prepareStatement("SELECT * FROM metric_data WHERE EventId = ? AND UserId = ?");
                dataStatement.setInt(1, eventId);
                dataStatement.setInt(2, id);
                ResultSet dataRs = dataStatement.executeQuery();
                
                Vector<MetricData> data = new Vector();
                while(dataRs.next()){
                    MetricData m = new MetricData();
                    m.setData(dataRs.getInt("RecordedValue"));
                    m.setDay(dataRs.getDate("DateTime"));
                    m.setEventId(dataRs.getInt("EventId"));
                    data.add(m);
                }
                
                String json = "{"
                            +"chart: {"
                                +"renderTo: 'example_chart',"
                                +"type: 'line',"
                                +"marginRight: 130,"
                                +"marginBottom: 25"
                            +"},"
                            +"title: {"
                                +"text: 'eventName',"
                                +"x: -20"
                            +"},"
                            +"subtitle: {"
                                +"text: 'subtitle',"
                                +"x: -20"
                            +"},"
                            +"xAxis: {"
                                +"categories: [";
                                    for(int i = 0; i < data.size(); i++){
                                        json += "'"+data.get(i).getDay()+"',";
                                    }
                                    json = json.substring(0,json.length()-1);
                           json+="]"
                            +"},"
                            +"yAxis: {"
                                +"title: {"
                                    +"text: 'Metric'"
                                +"},"
                                +"plotLines: [{"
                                    +"value: 0,"
                                    +"width: 1,"
                                    +"color: '#808080'"
                                +"}]"
                            +"},"
                            +"tooltip: {"
                                +"formatter: function() {"
                                        +"return '<b>'+ this.series.name +'</b><br/>'+"
                                        +"this.x +': '+ this.y +'°C';"
                                +"}"
                            +"},"
                            +"legend: {"
                                +"layout: 'vertical',"
                                +"align: 'right',"
                                +"verticalAlign: 'top',"
                                +"x: -10,"
                                +"y: 100,"
                                +"borderWidth: 0"
                            +"},"
                            +"series: [{"
                                +"name: '"+name+"',"
                                +"data: [";
                                for(int i = 0; i < data.size(); i++){
                                    json+=data.get(i).getData()+",";
                                }
                                json = json.substring(0,json.length()-1);
                          json+="]"
                            +"}]"
                        +"}";
                
                response.getWriter().print(json);
                
                
            }else if("static".equalsIgnoreCase(type)){
                
                PreparedStatement dataStatement = con.prepareStatement("SELECT * FROM static_data WHERE EventId = ? AND UserId = ?");
                dataStatement.setInt(1, eventId);
                dataStatement.setInt(2, id);
                
                System.out.println(id);
                ResultSet dataRs = dataStatement.executeQuery();
                
                Vector<StaticData> data = new Vector();
                
                while(dataRs.next()){
                    StaticData s = new StaticData();
                    s.setCompleted(dataRs.getInt("Completed"));
                    s.setDay(dataRs.getDate("DateTime"));
                    s.setEventId(dataRs.getInt("EventId"));
                    data.add(s);
                }
                
                double daysCompleted = 0;
                
                for(int i = 0; i < data.size(); i++){
                    if(data.get(i).getCompleted() == true)
                        daysCompleted++;
                }
                
                double completionPercentage = (daysCompleted/data.size())*100;
                
                String json = "";
                  
                json = ""   
                    +"{"
                        +"chart: {"
                        +"renderTo: 'example_chart',"
                        +"plotBackgroundColor: null,"
                        +"plotBorderWidth: null,"
                        +"plotShadow: false"
                    +"},"
                    +"title: {"
                        +"text: '"+name+"'"
                    +"},"
                    +"tooltip: {"
                        +"formatter: function() {"
                            +"return '<b>'+ this.point.name +'</b>: '+ this.percentage +' %';"
                        +"}"
                    +"},"
                    +"plotOptions: {"
                        +"pie: {"
                            +"allowPointSelect: true,"
                            +"cursor: 'pointer',"
                            +"dataLabels: {"
                                +"enabled: true,"
                                +"color: '#000000',"
                                +"connectorColor: '#000000',"
                                +"formatter: function() {"
                                    +"return '<b>'+ this.point.name +'</b>: '+ this.percentage +' %';"
                                +"}"
                            +"}"
                        +"}"
                    +"},"
                    +"series: [{"
                        +"type: 'pie',"
                        +"name: 'Completed',"
                        +"data: ["
                            +"{"
                                +"name: 'Complete',"
                                +"y: "+completionPercentage+","
                                +"sliced: true,"
                                +"selected: true"
                            +"},"
                            +"{"
                                +"name: 'Incomplete',"
                                +"y: "+(100-completionPercentage)+","
                                +"sliced: false,"
                                +"selected: false"
                            +"}"
                        +"]"
                    +"}]"
                +"}";
            
                response.getWriter().print(json);
            }
            
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            try{
                con.close();
            }catch(Exception e){
                
            }
        }
        
    }
    
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
    
}
